<template>
  <div class="main-box">
    <TreeFilter
      label="name"
      id="_id"
      title="组织"
      :data="treeFilterData"
      :default-value="initParam.condition.orgId"
      @change="changeTreeFilter"
    />
    <div class="table-box">
      <ProTable
        ref="proTable"
        :indent="20"
        :highlight-current-row="true"
        row-key="_id"
        :columns="columns"
        :request-api="getTableList"
        :request-auto="false"
        :search-col="{ xs: 2, sm: 3, md: 3, lg: 4, xl: 4 }"
        :init-param="initParam"
      >
        <!-- 表格 header 按钮 -->
        <template #tableHeader>
          <el-button type="primary" :icon="Download" plain @click="downloadFile">导出数据</el-button>
          <el-button type="primary" :icon="Refresh" plain @click="addNewUser">同步新增用户</el-button>
        </template>
        <template #manage_user_rushjob="scope">
          <user-select
            @change="onPropertyChangeSave(scope.row, 'manage_user_rushjob')"
            @clear="onPropertyClearSave(scope.row, 'manage_user_rushjob')"
            placeholder="请选择"
            v-model="scope.row.manage_user_rushjob"
          ></user-select>
        </template>
        <template #manage_user_performance_main="scope">
          <user-select
            @change="onPropertyChangeSave(scope.row, 'manage_user_performance_main')"
            @clear="onPropertyClearSave(scope.row, 'manage_user_performance_main')"
            placeholder="请选择"
            v-model="scope.row.manage_user_performance_main"
          ></user-select>
        </template>
        <template #manage_user_performance_sub="scope">
          <user-select
            @change="onPropertyChangeSave(scope.row, 'manage_user_performance_sub')"
            @clear="onPropertyClearSave(scope.row, 'manage_user_performance_sub')"
            placeholder="请选择"
            v-model="scope.row.manage_user_performance_sub"
          ></user-select>
        </template>
        <template #crossRate_main="scope">
          <common-select
            :data="crossRateList"
            v-model="scope.row.crossRate_main"
            @change="onPropertyChangeSave(scope.row, 'crossRate_main')"
            @clear="onPropertyClearSave(scope.row, 'crossRate_main')"
          ></common-select>
        </template>
        <template #crossRate_sub="scope">
          <common-select
            :data="crossRateList"
            v-model="scope.row.crossRate_sub"
            @change="onPropertyChangeSave(scope.row, 'crossRate_sub')"
            @clear="onPropertyClearSave(scope.row, 'crossRate_sub')"
          ></common-select>
        </template>
        <!-- 表格操作 -->
        <template #operation="scope">
          <el-button type="primary" link :icon="Refresh" @click="updateOrg(scope.row)">更新</el-button>
          <el-button type="primary" link :icon="Delete" @click="deleteManageUser(scope.row)">删除</el-button>
        </template>
      </ProTable>
    </div>
  </div>
</template>

<script setup lang="tsx" name="useProTable">
import { ref, reactive, onMounted, computed } from "vue";
import { ExportObj, Users, ManageUser, Org } from "@/api/types/base";
import { Download, Delete, Refresh } from "@element-plus/icons-vue";
import userSelect from "@/components/SelectFilter/user-select.vue";
import commonSelect from "@/components/SelectFilter/common-select.vue";
import ProTable from "@/components/ProTable/index.vue";
import TreeFilter from "@/components/TreeFilter/index.vue";
import { ProTableInstance, ColumnProps } from "@/components/ProTable/interface";
import apiService from "@/api/services/apiService";
import { useDateFormat } from "@vueuse/core";
import { useDownload } from "@/hooks/useDownload";
import { ExportColType } from "@/enums/sysEnum";
import { ElMessage, ElMessageBox } from "element-plus";
import { useDataStore } from "@/stores/modules/data";
import { useHandleData } from "@/hooks/useHandleData";
const dataStore = useDataStore();
// ProTable 实例
const proTable = ref<ProTableInstance>();

// 如果表格需要初始化请求参数，直接定义传给 ProTable (之后每次请求都会自动带上该参数，此参数更改之后也会一直带上，改变此参数会自动刷新表格数据)
const initParam = reactive({
  condition: { orgId: "" }
});

const initVar = reactive({
  tbName: "manage_user"
});

const crossRateList = computed(() => dataStore.getEnumByCsName("crossRate"));
onMounted(() => {
  dataStore.findEnumByCsName("crossRate");
  getTreeList();
});

// 如果你想在请求之前对当前请求参数做一些操作，可以自定义如下函数：params 为当前所有的请求参数（包括分页），最后返回请求列表接口
// 默认不做操作就直接在 ProTable 组件上绑定	:requestApi="getUserList"
const getTableList = async (params: any) => {
  return new Promise(async resolve => {
    // 获取管理权限数据
    // const userIds = users.data.content.map(item => item._id);
    const manageUsers = await apiService.findPage<ManageUser>(initVar.tbName, params.condition, params.options);

    if (manageUsers.data.content.length === 0) {
      const { data } = await apiService.find<Users[]>("users", params.condition);

      // 获取组织信息，用于第一次未设置，根据组织负责人初始化管理权限
      const orgIds = data.map(item => item.orgId);
      const orgs = await apiService.find<Org[]>("orgs", { _id: { $in: orgIds } });
      const orgMap = new Map();
      orgs.data.forEach(org => orgMap.set(org._id, org));

      let initManageUsers: any = [];
      data.forEach(user => {
        let org = orgMap.get(user.orgId);
        initManageUsers.push({
          userId: user._id,
          userName: user.userName,
          orgId: user.orgId,
          manage_user_rushjob: org.leader,
          manage_user_performance_main: org.leader,
          crossRate_main: "1"
        });
      });
      if (initManageUsers.length > 0) {
        let saveManageUserList = await apiService.saveList<ManageUser>(initVar.tbName, initManageUsers);
        if (saveManageUserList.data && saveManageUserList.data.ops) {
          manageUsers.data.content = saveManageUserList.data.ops;
        }
      }
    }
    resolve(manageUsers);
  });
};

const addNewUser = async () => {
  if (proTable.value?.tableData && initParam.condition.orgId) {
    const { data } = await apiService.find<Users[]>("users", { orgId: initParam.condition.orgId });
    let newManageUsers: any = [];
    data.forEach(user => {
      if (!proTable.value?.tableData.find(item => item.userId === user._id)) {
        newManageUsers.push({
          userId: user._id,
          userName: user.userName,
          orgId: user.orgId,
          crossRate_main: "1"
        });
      }
    });
    if (newManageUsers.length > 0) {
      let saveManageUserList = await apiService.saveList<ManageUser>(initVar.tbName, newManageUsers);
      if (saveManageUserList.data && saveManageUserList.data.ops) {
        proTable.value?.tableData.push(...saveManageUserList.data.ops);
      }
      ElMessage.success("更新成功");
    } else {
      ElMessage.success("无新增用户");
    }
  }
};

const updateOrg = async (row: ManageUser) => {
  const curUser = await apiService.findOne<Users>("users", { _id: row.userId });
  if (curUser.data) {
    if (curUser.data.orgId !== row.orgId) {
      row.orgId = curUser.data.orgId;
      await apiService.updateById(initVar.tbName, row);
      ElMessage.success("更新成功");
    } else {
      ElMessage.info("无需更新，组织未发生变化");
    }
  } else {
    ElMessage.info("该用户已不存在");
  }
};

const deleteManageUser = async (params: ManageUser) => {
  await useHandleData(apiService.deleteById, initVar.tbName, params._id, `删除【${params.userName}】`);
  proTable.value?.getTableList();
};

const treeFilterData = ref<any>([]);
const getTreeList = async () => {
  const { data } = await apiService.findTree("orgs", {}, { sort: { sort: 1 } });
  treeFilterData.value = data;
  initParam.condition.orgId = treeFilterData.value[0]._id;
};

// 树形筛选切换
const changeTreeFilter = (val: string) => {
  proTable.value!.pageable.pageNum = 1;
  initParam.condition.orgId = val;
};

// 表格配置项
const columns = reactive<ColumnProps<Users>[]>([
  { type: "index", label: " ", width: 60 },
  { prop: "userName", label: "用户名", search: { el: "input", like: true }, width: 100 },
  {
    prop: "orgId",
    label: "所属组织",
    width: 200,
    // 字典请求携带参数
    enum: treeFilterData,
    fieldNames: { label: "name", value: "_id" }
  },
  {
    prop: "rushjob",
    label: "突击管理",
    _children: [{ prop: "manage_user_rushjob", label: "审核人" }]
  },
  {
    prop: "rushjob",
    label: "绩效管理",
    _children: [
      { prop: "manage_user_performance_main", label: "主评人" },
      {
        prop: "crossRate_main",
        label: "评估占比",
        // enum: () => apiService.findClassify("crossRate"),
        fieldNames: { label: "name", value: "value" }
      },
      { prop: "manage_user_performance_sub", label: "辅评人" },
      {
        prop: "crossRate_sub",
        label: "评估占比",
        // enum: () => dataStore.findEnumByCsName("crossRate"),
        fieldNames: { label: "name", value: "value" }
      }
    ]
  },
  { prop: "operation", label: "操作", fixed: "right", width: 180 }
]);

// 导出数据
const downloadFile = async () => {
  ElMessageBox.confirm("确认导出数据?", "温馨提示", { type: "warning" }).then(() =>
    useDownload(apiService.commonExport, `用户角色-${useDateFormat(new Date(), "YYYY-MM-DD").value}`, "", getExcelConfig(), false)
  );
};

const getExcelConfig = (): ExportObj => {
  let newParams = JSON.parse(JSON.stringify(proTable.value?.totalParam));
  return {
    params: newParams,
    tableName: "users",
    keyPropName: "_id",
    enumTypes: ["SEX", "DATA_STATE"],
    tableConfigs: [
      { tableName: "orgs", fields: ["_id", "name"] },
      { tableName: "roles", fields: ["_id", "name"] },
      { tableName: "userRoles" }
    ],
    header: [
      { header: "序号", width: 6, ext: { prop: "index", type: ExportColType.INDEX } },
      {
        header: "姓名",
        width: 8,
        ext: { prop: "userName", type: ExportColType.DEFAULT }
      },
      {
        header: "性别",
        width: 8,
        ext: { prop: "sex", type: ExportColType.ENUM, key: "SEX" }
      },
      { header: "组织", width: 15, ext: { prop: "orgId", type: ExportColType.TABLE, key: "orgs" } },
      { header: "邮箱", width: 30, ext: { prop: "email", type: ExportColType.DEFAULT } },
      { header: "状态", width: 10, ext: { prop: "state", type: ExportColType.ENUM, key: "DATA_STATE" } },
      { header: "角色", width: 30, ext: { prop: "role", func: "roleProcess", type: ExportColType.CUSTOM } }
    ]
  };
};

const onPropertyChangeSave = async (row: ManageUser, columnName: string) => {
  if (row && row._id && row[columnName]) {
    let data = { _id: row._id };
    data[columnName] = row[columnName];
    await apiService.updateById(initVar.tbName, data);
    ElMessage.success("更新成功");
  }
};

const onPropertyClearSave = async (row: ManageUser, columnName: string) => {
  if (row && row._id) {
    let data = { _id: row._id };
    data[columnName] = "";
    console.log(data);
    await apiService.updateById(initVar.tbName, data);
    ElMessage.success("更新成功");
  }
};
</script>
